package com.novellotus.iov.carvice.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.google.gson.JsonObject;
import com.jakewharton.rxbinding2.widget.RxTextView;
import com.novellotus.httploadingview.LoadingView;
import com.novellotus.iov.carvice.R;
import com.novellotus.iov.carvice.bean.RxVehicleDetail;
import com.novellotus.iov.carvice.bean.RxVehiclesType;
import com.novellotus.iov.carvice.retrofit.BaseArrayEntity;
import com.novellotus.iov.carvice.retrofit.BaseArrayObserver;
import com.novellotus.iov.carvice.retrofit.BaseEntity;
import com.novellotus.iov.carvice.retrofit.BaseObserver;
import com.novellotus.iov.carvice.retrofit.RetrofitFactory;
import com.novellotus.iov.carvice.retrofit.RxSchedulers;
import com.novellotus.iov.carvice.rxjava.MyObserver;
import com.novellotus.iov.carvice.utils.MyUtils;
import com.novellotus.iov.carvice.utils.MyViewUtils;
import com.novellotus.iov.carvice.utils.SharedPreferencesUtils;
import com.novellotus.iov.carvice.view.NoDayDatePickerDialog;
import com.rengwuxian.materialedittext.MaterialEditText;

import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function3;
import okhttp3.RequestBody;

public class AddStorageCarActivity extends BaseActivity implements LoadingView.OnBtnClickListener {

    @BindView(R.id.tv_tittle)
    TextView tv_tittle;
    @BindView(R.id.tv_production_value)
    TextView tv_production_value;
    @BindView(R.id.ln_choose)
    LinearLayout ln_choose;
    @BindView(R.id.img_ln_choose_arrow)
    ImageView img_ln_choose_arrow;
    @BindView(R.id.tv_model_value)
    TextView tv_model_value;
    @BindView(R.id.tv_notice_model_value)
    TextView tv_notice_model_value;
    @BindView(R.id.edt_vin)
    MaterialEditText edt_vin;
    @BindView(R.id.edt_total_weight)
    MaterialEditText edt_total_weight;
    @BindView(R.id.edt_vehicle_weight)
    MaterialEditText edt_vehicle_weight;
    @BindView(R.id.edt_battery_capacity)
    MaterialEditText edt_battery_capacity;
    @BindView(R.id.edt_battery_voltage)
    MaterialEditText edt_battery_voltage;
    @BindView(R.id.edt_motor_num)
    MaterialEditText edt_motor_num;
    @BindView(R.id.edt_motor_power)
    MaterialEditText edt_motor_power;
    @BindView(R.id.edt_wheelbase)
    MaterialEditText edt_wheelbase;
    @BindView(R.id.edt_vehicle_code)
    MaterialEditText edt_vehicle_code;
    @BindView(R.id.edt_mark)
    MaterialEditText edt_mark;
    @BindView(R.id.btn_submit)
    TextView btn_submit;
    @BindView(R.id.loadingView)
    LoadingView loadingView;
    @BindView(R.id.img_model_arrow)
    ImageView img_model_arrow;
    @BindView(R.id.img_date_arrow)
    ImageView img_date_arrow;
    @BindView(R.id.tv_detail)
    TextView tv_detail;
    @BindView(R.id.tv_base)
    TextView tv_base;
    String typeId = "";//车型id
    Calendar calendar;
    boolean isShow = true;
    String eCode;
    String rCode;
    String carId;
    String look;
    List<RxVehiclesType> rxVehiclesTypeList;
    String checkVin = "^[A-Z0-9]{17}$";

    @Override
    protected void initContentView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_add_car);
    }

    @Override
    public void init() {
        loadingView.setLoadingModel(LoadingView.MODEL_ALERT);
        loadingView.setOnBtnClickListener(this);
        loadingView.setBackgroundColor(this.getResources().getColor(R.color.white));
        initObservable();
        calendar = Calendar.getInstance();
        eCode = getIntent().getStringExtra("eCode");
        rCode = getIntent().getStringExtra("rCode");
        carId = getIntent().getStringExtra("carId");
        look = getIntent().getStringExtra("look");
        if (look == null) {
            if (carId != null) {
                getDetail();
                tv_tittle.setText("入库车辆详情");
                btn_submit.setText("修改");
            } else {
                tv_tittle.setText("新增入库车辆");
            }
            getList();
        } else {
            tv_tittle.setText("入库车辆详情");
            img_model_arrow.setVisibility(View.GONE);
            img_date_arrow.setVisibility(View.GONE);
            btn_submit.setVisibility(View.GONE);
            tv_base.setText("基础信息");
            tv_detail.setText("详细信息");
            noFocaus();
            getDetail();
        }


    }

    private void noFocaus() {
        edt_vin.setFocusable(false);
        edt_total_weight.setFocusable(false);
        edt_vehicle_weight.setFocusable(false);
        edt_battery_capacity.setFocusable(false);
        edt_battery_voltage.setFocusable(false);
        edt_motor_num.setFocusable(false);
        edt_motor_power.setFocusable(false);
        edt_wheelbase.setFocusable(false);
        edt_vehicle_code.setFocusable(false);
        edt_mark.setFocusable(false);
        edt_vin.setFocusable(false);
        edt_vin.setFocusable(false);
    }

    @OnClick(R.id.img_back)
    void back() {
        finish();
    }


    /**
     * 获取车型列表
     */
    public void getList() {
        Observable<BaseArrayEntity<RxVehiclesType>> observable = RetrofitFactory.getInstance().vehiclesTypes(SharedPreferencesUtils.getKey(this)[0], eCode, rCode);
        observable.compose(RxSchedulers.<BaseArrayEntity<RxVehiclesType>>compose())
                .subscribe(new BaseArrayObserver<RxVehiclesType>(this) {

                    @Override
                    public void onSuccess(List<RxVehiclesType> t) {
                        loadingView.success();
                        rxVehiclesTypeList = t;
                    }

                    @Override
                    public void onFail(int code, String msg) {
                        loadingView.empty(msg, true);
                    }

                    @Override
                    public void onError(String msg) {
                        loadingView.empty(msg, true);
                    }

                });
    }

    /**
     * 获取车辆详情
     */
    RxVehicleDetail rxVehicleDetail;
    public void getDetail() {
        Observable<BaseEntity<RxVehicleDetail>> observable = RetrofitFactory.getInstance().vehiclesDetail(carId, SharedPreferencesUtils.getKey(this)[0], eCode, rCode);
        observable.compose(RxSchedulers.<BaseEntity<RxVehicleDetail>>compose())
                .subscribe(new BaseObserver<RxVehicleDetail>(this) {
                    @Override
                    public void onSuccess(RxVehicleDetail t) {
                        loadingView.success();
                        rxVehicleDetail = t;
                        if (t != null)
                            initEdit(t);
                    }

                    @Override
                    public void onFail(int code, String msg) {
                        loadingView.empty(msg, true);
                    }

                    @Override
                    public void onError(String msg) {
                        loadingView.empty(msg, true);
                    }
                });
    }

    /**
     * * "id": "车辆ID", 若是新增车辆 此ID为NULL
     * "vin": "LDPGABA0BHF160163", 车架号
     * "typeId":"7yQMoNQqRxFmxNFdK53EcL",车型ID
     * "remark": "测试车辆", 备注
     * "car_code": "C12832", 整车编号 必填
     * "made_date": "2017-12",生产日期 格式为2017-12 必填
     * "wheelbase": 12,轴距
     * "maximum_permissible_total_mass": 12, 最大允许总质量
     * "gross_mass": 12, 整车质量
     * "power_cell_capacity": 1,动力电池容量
     * "power_cell_working_voltage": 1,动力电池工作电压
     * "main_drive_motor_model": D123-32,主驱动电机型号
     * "main_drive_motor_power": 3 主驱动电机功率
     */
    private void initEdit(RxVehicleDetail t) {

        typeId = t.getCarType().getId();
        edt_vin.setText(t.getVin());
        tv_model_value.setText(t.getCarType().getName());
        tv_notice_model_value.setText(t.getCarType().getCode());
        if (look == null) {
            tv_production_value.setText((t.getMade_date() == null || t.getMade_date().length() == 0) ? "请选择生产日期" : t.getMade_date());
        } else {
            tv_production_value.setText((t.getMade_date() == null || t.getMade_date().length() == 0) ? "" : t.getMade_date());
        }

        edt_total_weight.setText(t.getMaximum_permissible_total_mass());
        edt_vehicle_weight.setText(t.getGross_mass());
        edt_battery_capacity.setText(t.getPower_cell_capacity());
        edt_battery_voltage.setText(t.getPower_cell_working_voltage());
        edt_vehicle_code.setText(t.getCar_code());
        edt_motor_num.setText(t.getMain_drive_motor_model());
        edt_motor_power.setText(t.getMain_drive_motor_power());
        edt_wheelbase.setText(t.getWheelbase());
        edt_mark.setText(t.getRemark());

    }

    Calendar c = Calendar.getInstance();

    @OnClick(R.id.rlt_data)
    void chooseMonthYear() {
        MyUtils.hideInput(this);
        if (look == null) {
            NoDayDatePickerDialog dayDatePickerDialog = new NoDayDatePickerDialog(this, 0, new NoDayDatePickerDialog.OnDateSetListener() {
                @Override
                public void onDateSet(DatePicker datePicker, int year, int month, int i2) {
                    if (correctData(year, month)) {
                        String monthStr = "";
                        if (month+1 < 10) {
                            monthStr = "0" + (month + 1);
                        } else {
                            monthStr = (month + 1) + "";
                        }

                        tv_production_value.setText(year + "-" + monthStr);
                    } else {
                        MyUtils.showToast(AddStorageCarActivity.this, "生产日期不能大于当前");
                    }
                }
            }, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DATE));
            dayDatePickerDialog.show();
        }

    }

    private boolean correctData(int year, int month) {

        if (c.get(Calendar.YEAR) < year) {
            return false;
        } else if (c.get(Calendar.YEAR) == year && c.get(Calendar.MONTH) < month) {
            return false;
        }

        return true;
    }

    @OnClick(R.id.rlt_choose)
    void showChoose() {
        isShow = !isShow;
        if (isShow) {
            img_ln_choose_arrow.setBackgroundResource(R.mipmap.icon_detail_arrow_down);
            ln_choose.setVisibility(View.VISIBLE);
        } else {
            img_ln_choose_arrow.setBackgroundResource(R.mipmap.icon_detail_arrow);
            ln_choose.setVisibility(View.GONE);
        }
    }

    /**
     * "id": "车辆ID", 若是新增车辆 此ID为NULL
     * "vin": "LDPGABA0BHF160163", 车架号
     * "typeId":"7yQMoNQqRxFmxNFdK53EcL",车型ID
     * "remark": "测试车辆", 备注
     * "car_code": "C12832", 整车编号 必填
     * "made_date": "2017-12",生产日期 格式为2017-12 必填
     * "wheelbase": 12,轴距
     * "maximum_permissible_total_mass": 12, 最大允许总质量
     * "gross_mass": 12, 整车质量
     * "power_cell_capacity": 1,动力电池容量
     * "power_cell_working_voltage": 1,动力电池工作电压
     * "main_drive_motor_model": D123-32,主驱动电机型号
     * "main_drive_motor_power": 3 主驱动电机功率
     */
    @OnClick(R.id.btn_submit)
    void submit() {
        JsonObject jsonObject = new JsonObject();
        if (carId != null) {
            jsonObject.addProperty("id", carId);
        }
        jsonObject.addProperty("vin", edt_vin.getText().toString());
        jsonObject.addProperty("typeId", typeId);
        jsonObject.addProperty("made_date", tv_production_value.getText().toString());
        jsonObject.addProperty("maximum_permissible_total_mass", edt_total_weight.getText().toString());
        jsonObject.addProperty("gross_mass", edt_vehicle_weight.getText().toString());
        jsonObject.addProperty("power_cell_capacity", edt_battery_capacity.getText().toString());
        jsonObject.addProperty("power_cell_working_voltage", edt_battery_voltage.getText().toString());
        jsonObject.addProperty("main_drive_motor_model", edt_motor_num.getText().toString());
        jsonObject.addProperty("main_drive_motor_power", edt_motor_power.getText().toString());
        jsonObject.addProperty("wheelbase", edt_wheelbase.getText().toString());
        jsonObject.addProperty("car_code", edt_vehicle_code.getText().toString());
        jsonObject.addProperty("remark", edt_mark.getText().toString());

        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("text/plain; charset=utf-8"), jsonObject.toString());
        Observable<BaseEntity<Object>> observable = RetrofitFactory.getInstance().storage(SharedPreferencesUtils.getKey(this)[0], eCode, rCode, body);
        observable.compose(RxSchedulers.<BaseEntity<Object>>compose())
                .subscribe(new BaseObserver<Object>(this) {

                    @Override
                    public void onSuccess(Object rxVehicle) {
                        if (carId != null) {
                            MyUtils.showToast(AddStorageCarActivity.this, "修改成功");
                        } else {
                            MyUtils.showToast(AddStorageCarActivity.this, "新增成功");
                        }

                    }

                    @Override
                    public void onFail(int code, String msg) {
                        MyUtils.showToast(AddStorageCarActivity.this, msg);
                    }

                    @Override
                    public void onError(String msg) {
                        MyUtils.showToast(AddStorageCarActivity.this, msg);
                    }
                });
    }


    @OnClick(R.id.rlt_car_model)
    public void showModelPicker() {
        MyUtils.hideInput(this);
        if (rxVehiclesTypeList != null && look == null) {
            if (rxVehiclesTypeList.size() >= 0) {
                OptionsPickerView pvOptions = new OptionsPickerView.Builder(AddStorageCarActivity.this, new OptionsPickerView.OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int options2, View v) {
                        //返回的分别是三个级别的选中位置
                        String tx = rxVehiclesTypeList.get(options1).getPickerViewText();
                        tv_notice_model_value.setText(rxVehiclesTypeList.get(options1).getCode());
                        typeId = rxVehiclesTypeList.get(options1).getId();
                        tv_model_value.setText(tx);
                    }
                })
                        .setTitleText("选择车型")
                        .setDividerColor(Color.BLACK)
                        .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                        .setContentTextSize(20)
                        .setOutSideCancelable(false)// default is truet
                        .build();
                pvOptions.setPicker(rxVehiclesTypeList);
                //  pvOptions.wheelOptions.setCurrentItems(0);
                pvOptions.show();
            } else {
                MyUtils.showToast(this, "暂无车型数据");
            }
        }

    }


    /**
     * 表单验证
     */
    private Observable<CharSequence> ObservableVin;
    private Observable<CharSequence> ObservableModel;
    private Observable<CharSequence> ObservableDate;

    private void initObservable() {
        ObservableVin = RxTextView.textChanges(edt_vin);
        ObservableModel = RxTextView.textChanges(tv_model_value);
        ObservableDate = RxTextView.textChanges(tv_production_value);


        ObservableVin.compose(RxSchedulers.<CharSequence>lifecycle(this))
                .compose(RxSchedulers.<CharSequence>compose())
                .subscribe(new MyObserver<CharSequence>() {
                    @Override
                    public void onNext(CharSequence pass) {
                        super.onNext(pass);
                        if (pass.length() == 17) {
                            if (MyUtils.isVin(pass.toString())) {
                                edt_vin.setError(null);
                            } else {
                                edt_vin.setError("车辆识别代码格式有误");
                            }

                        }
                    }
                });
        Observable.combineLatest(ObservableVin, ObservableModel, ObservableDate, new Function3<CharSequence, CharSequence, CharSequence, Boolean>() {
            @Override
            public Boolean apply(CharSequence vin, CharSequence model, CharSequence date) throws Exception {
                return MyUtils.isVin(vin.toString()) && model.length() > 0 && (!date.toString().equals("请选择生产日期") && !date.toString().equals(""));
            }
        }).compose(RxSchedulers.<Boolean>lifecycle(AddStorageCarActivity.this)).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean pass) throws Exception {
                if (pass) {
                    MyViewUtils.setButtonClickable(btn_submit, true);
                } else {
                    MyViewUtils.setButtonClickable(btn_submit, false);
                }
            }
        });
    }

    @Override
    public void onReload() {
        if (look == null) {
            if (rxVehiclesTypeList == null) {
                getList();
            }
        }
        if (rxVehicleDetail == null) {
            getDetail();
        }


    }
}
